<?php

namespace App\Providers;

use App\Models\Coin;
use App\Models\CoinRecord;
use App\Models\GameRecord;
use App\Models\Payment;
use App\Models\User;
use App\Services\Doll;
use App\Services\EchoServer;
use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('phone', function ($attribute, $value, $parameters, $validator) {
            return is_phone($value);
        });

        $this->relationMorph();
        
//        $this->logDBQuery();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ('local' == $this->app->environment()) {
            $this->app->register(DebugbarServiceProvider::class);
        }
        
        $this->app->singleton(EchoServer::class, function () {
            return new EchoServer('queue');
        });
        
        $this->app->singleton(Doll::class);
    }

    /**
     * 定义多态关系的类型
     */
    private function relationMorph()
    {
        Relation::morphMap([
            CoinRecord::TYPE_GAME_RECORD => GameRecord::class,
            CoinRecord::TYPE_PAYMENT => Payment::class,
            CoinRecord::TYPE_REGISTER => User::class,
            Payment::TYPE_COIN => Coin::class,
        ]);
    }
    
    /**
     * 把 sql 写入 log
     */
    protected function logDBQuery()
    {
        \DB::listen(function ($sql) {
            /** @var \Illuminate\Database\Events\QueryExecuted $sql */
            
            // 解析绑定的数据，然后把 sql 写入 log
            foreach ($sql->bindings as $i => $binding) {
                if ($binding instanceof \DateTime) {
                    $sql->bindings[$i] = $binding->format("'Y-m-d H:i:s'");
                } else {
                    if (is_string($binding)) {
                        $sql->bindings[$i] = "'$binding'";
                    }
                }
            }
            
            $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
            
            $query = vsprintf($query, $sql->bindings);
            
            logger($query);
            logger('---------------------------------------------');
        });
    }
}
